#include "Map.h"

using namespace std;

Map::Map()
{
	m_dimension.first = 0;
	m_dimension.second = 0;
	
	//m_typeCarte = plaine;
	
	//initialisation de la carte
}

Map::Map(std::string path)
{
	string terrain;
	
	TiXmlDocument doc(path.c_str());
	if(!doc.LoadFile())
	{
		exit(0);
	}
	//se place sur le premier noeud
	TiXmlHandle hdl(&doc);
	TiXmlHandle hdroot(0);
	hdroot = hdl.FirstChildElement();
	
	
	TiXmlElement *config = hdroot.FirstChildElement("configuration").FirstChildElement().Element();
	TiXmlElement *zone = hdroot.FirstChildElement("zone").FirstChildElement().Element();

	if(!config || !zone){
		cerr << "le noeud à atteindre n'existe pas, mauvais format de XML" << endl;
		exit(0);
	}
	// bloque de configuration
	{ 
		int  x,y;
		config->QueryIntAttribute("x", &x);
		config->QueryIntAttribute("y", &y);
		config = config->NextSiblingElement(); // element suivant
		terrain = config->Attribute("name");
		m_dimension.first = x;
		m_dimension.second = y;
	}
	
	//initialisation de la carte
	m_map.resize(m_dimension.first);
	for(int i = 0 ; i < m_dimension.first ; i++ )
		m_map[i].resize(m_dimension.second);
	
	//boucle qui definie le type de case par defaut
	for(int i = 0 ; i < m_dimension.first; i++)
	{
		for(int j = 0 ; j < m_dimension.second ;j++)
		{
			setTypeCase(terrain,&m_map[i][j]);
		}
	}
	m_map[0][0]->dessiner();
	// bloque de zone, attribue chaque case spéciale
	{
		int x,y,x2,y2;
		while(zone)
		{
			zone->QueryIntAttribute("x", &x);
			zone->QueryIntAttribute("y", &y);
			zone->QueryIntAttribute("x2", &x2);
			zone->QueryIntAttribute("y2", &y2);
			terrain = zone->Value();
			//creation des zones dans la map
			int tmp = y; 
			while(x<=x2)
			{
				while(y<=y2)
				{
					setTypeCase(terrain,&m_map[y][x]);
					y++;
				}
				y=tmp;
				x++;
			}
			zone = zone->NextSiblingElement();
		}
	}
}

int Map::getX()
{
	return m_dimension.first;
}
int Map::getY()
{
	return m_dimension.second;
}
pair<int,int> Map::getDimension()
{
	return m_dimension;
}
void Map::setX(int x)
{
	m_dimension.first = x;
}
void Map::setY(int y)
{
	m_dimension.second = y;
}
void Map::setDimension(int x, int y)
{
	m_dimension.first = x;
	m_dimension.second = y;
}

std::vector<std::vector<Case *> > Map::getMap()
{
	return m_map;
}
//~ string Map::getTypeCarte()
//~ {
	//~ return m_typeCarte.first;
//~ }

void Map::setTypeCase(string type, Case** maCase)
{
	if(type == "plaine")
		*maCase = new Plaine();
	else if(type == "eau")
		*maCase = new Eau();
	else if(type == "arbre")
		*maCase = new Arbre();
	else if(type == "porte")
		*maCase = new Porte();
	else if(type == "mur")
		*maCase = new Mur();
	else if(type == "table")
		*maCase = new Table();
	else
		*maCase = new Case();
}
//~ 
//~ Case Map::getElemTypeCarte()
//~ {
	//~ return m_typeCarte.second;
//~ }
//~ void Map::setElemTypeCarte(Case* type)
//~ {
	//~ m_typeCarte.second = *type;
//~ }




